<template>
  <a-row>
    <a-col :span="7">
      <a-select 
        :value="mirror.value"
        @change="onMirrorTypeChange"
      >
        <a-select-option 
          v-for="item in mirrors" 
          :value="item.value"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
    </a-col>
    <a-col :span="16" :offset="1">
      <a-input :value="mirror.url" :disabled="urlDisabled" @change="onMirrorUrlChange" />
    </a-col>
  </a-row>
</template>

<script setup>
import { computed, defineModel } from 'vue'
import { Form } from 'ant-design-vue'

const mirror = defineModel('mirror')

const props = defineProps({
  mirrors: Array
})

const urlDisabled = computed(() => {
  return  mirror.value !== 'custom-mirror'
})

const formItemContext = Form.useInjectFormItemContext()

const triggerChange = (changedValue) => {
  mirror.value = changedValue
  formItemContext.onFieldChange()
}
const onMirrorTypeChange = (value) => {
  const mirror = props.mirrors.find(mirror => mirror.value === value);
  const url = mirror ? mirror.url : ''
  triggerChange({ value, url })
}
const onMirrorUrlChange = (event) => {
  const url = event.target.value;
  const value = mirror.value.value
  triggerChange({ value, url })
}
</script>
